package com.dq.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;

@Controller
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private DefaultKaptcha captchaProducer;

    @GetMapping("/generate")
    public void generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 生成验证码文本
        String captchaText = captchaProducer.createText();

        // 将验证码文本存储到Session中（你也可以存储到数据库或其他地方）
        request.getSession().setAttribute("captcha", captchaText);

        // 生成验证码图片
        BufferedImage bi = captchaProducer.createImage(captchaText);

        // 设置响应内容类型为图片
        response.setContentType("image/png");

        // 将验证码图片写入响应输出流
        ImageIO.write(bi, "png", response.getOutputStream());
    }
}
